﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text.RegularExpressions;
using LitJson;
using System.Linq;

[System.Serializable]
public class StoryDataManager : PersistentSingleton<StoryDataManager>
{
    public  List<Story> stories;

    private string storiesFile = "Stories";
    private string charactersFile = "Characters";
    private string[] filepath = { "/StreamingAssets/", ".json" };

    private string[] imagepath = { "Pictures/", "Charactor/", "CG/" };
    private string[] csvpath = { "/Resources/", ".csv", "Story" };


    public void CreatStory()
    {
        Story s = new Story();
        //s.Instantiate(stories.Count);        

        StoryCharacterData charactorData = new StoryCharacterData();
        stories.Add(s);
        
    }




    /*************************保存区域******************************/

    public void SaveData()
    {
        SaveStories();

    }
    public void SaveStories()
    {
        SaveListByJson<Story>(stories, storiesFile);
    }

    void SaveListByJson<T>(List<T> save, string filename)
    {
        //序列化过程（将Save对象转换为字节流） 

        //定义字符串filePath保存文件路径信息（就是在Assets中创建的一个文件夹名称为StreamFile,然后系统会给我创建一个byJson.json用于保存游戏信息）
        string filePath = Application.dataPath + filepath[0] + filename + filepath[1];
        //利用JsonMapper将save对象转换为Json格式的字符串(这里要引入命名空间using LitJson)
        string saveJsonStr = JsonMapper.ToJson(save);
        saveJsonStr = Regex.Unescape(saveJsonStr);

        //将这个字符串写入到文件中
        //创建一个StreamWriter,并将字符串写入到文件中
        StreamWriter sw = new StreamWriter(filePath);
        sw.Write(saveJsonStr);
        sw.Close();

        Debug.Log("保存成功");
    }

    /*************************读取区域******************************/
    public void LoadData()
    {
        LoadStories();
        //LoadCharacters();
    }
    public void LoadStories()
    {
        stories = LoadListByJson<Story>(stories, storiesFile);
    }

    public List<T> LoadListByJson<T>(List<T> save, string filename)
    {
        List<T> list = new List<T>();
        //定义字符串filePath读取文件路径信息（就是在Assets中读取一个文件夹名称为StreamFile里面的一个byJson.json保存游戏信息的文档）
        string filePath = Application.dataPath + filepath[0] + filename + filepath[1];

        //判断要读取的游戏文档信息是否存在
        if (File.Exists(filePath))
        {
            //创建一个StreamReader,用来读取流
            StreamReader sr = new StreamReader(filePath);
            //将读取到的流赋值给jsonStr
            string jsonStr = sr.ReadToEnd();
            //关闭
            sr.Close();

            jsonStr = Regex.Unescape(jsonStr);
            list = JsonMapper.ToObject<List<T>>(jsonStr);
            return list;
        }
        else
            return null;
    }

    /*************************故事导入区域******************************/
    public void LoadStoryCSV(string path)
    {
        CsvController csvController = CsvController.GetInstance();
        //csvController加载csv文件，单例模式，这个类只有一个对象，这个对象只能加载一个csv文件
        

        //Debug.Log(Application.dataPath + csvpath[0] + csvpath[2] + path + csvpath[1]);
        List<string[]>  stringList = csvController.loadFile(Application.dataPath + csvpath[0] + csvpath[2], path + csvpath[1]);
        List<ShortStory> list = new List<ShortStory>();
        int id_story = int.Parse(stringList[0][10]);       

        int type;
        int jumpLine;

        //根据索引读取csvController中的list（csv文件的内容）数据
        for (int n = 1; n < stringList.Count; n++)
        {
            ShortStory shortStory = new ShortStory();
            string[] s = { stringList[n][0], stringList[n][1], stringList[n][2] };
            type = int.Parse(stringList[n][4]);

            switch (type)
            {
                case 1:
                    shortStory.creatNewShortStory(stringList[n][3], s, type);
                    break;
                case 2:
                    shortStory.creatNewShortStory(stringList[n][3], s, type);
                    break;
                case 3:
                    jumpLine = int.Parse(stringList[n][5]);
                    shortStory.creatNewShortStory(stringList[n][3], s, type, jumpLine);
                    break;
                default:
                    break;
            }

            shortStory.id_shortStory = n.ToString();
            list.Add(shortStory);
        }


        Story story;
        if (id_story >= stories.Count)
        {
            Debug.Log(stories.Count);
            story = new Story();
            id_story = stories.Count;
            story.Instantiate(id_story, list);
            stories.Add(story);
        }
        else
            stories[id_story].Instantiate(id_story, list);
    }



    /*************************数据处理区域******************************/

    public Story GetStoryById(int id)
    {
        //遍历寻找对应id的剧情并返回，如无则返回null
        foreach (var s in stories)
        {
            if (s.id_story == id)
            {
                //s.CharacterData = LoadCharactorData(s);
                return s;
            }
        }
#if UNITY_EDITOR
        Debug.Log("超出边界，无此剧情");
#endif
        return null;
    }


    public Dictionary<string, StoryCharacterData> LoadCharactorData(Story story)
    {
        Dictionary<string, StoryCharacterData> charactorData = story.charactorData;

        string path = null;
        foreach (var v in story.id_charactor)
        {
            string id = v;

            char[] c = id.ToCharArray();
            if (c.Length > 0)
            {
                c = c.Skip(0).Take(3).ToArray();                    //取前3位字符
                string s = new string(c);

                if (s == "001")
                    path = imagepath[0] + imagepath[1] + id;
                else if (s == "002")
                    path = imagepath[0] + imagepath[2] + id;
                charactorData[id].setImage(Resources.Load(path, typeof(Sprite)) as Sprite);
                path = null;
            }            
        }
        return charactorData;
    }




}
